package com.wang.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.wang.io.Resource;
import com.wang.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by wangq on 2021/6/29.
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j解析配置文件，封装为Configuration
     *
     * @param inputStream 配置文件输入流
     * @return Configuration对象
     */
    public Configuration parseConfig(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        //  获取配置文件的根节点
        Element rootElement = document.getRootElement();

        // 把数据库配置文件的中property节点的信息遍历拿出 存放在Properties中
        List<Element> propertyElementList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElementList) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 把Properties中存储的数据库配置信息 添加到c3p0连接池中
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("userName"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        // 把数据库连接信息封装到Configuration中
        configuration.setDataSource(comboPooledDataSource);

        // 解析映射sqlMapper文件
        List<Element> mapperElementList = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElementList) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream mapperInputStream = Resource.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(mapperInputStream);
        }

        return configuration;
    }
}
